#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <ctime>
static int Data = 0;
pthread_rwlock_t _rwlock;
void *Reader(void *args)
{
    int *id = static_cast<int *>(args);
    while (true)
    {
        pthread_rwlock_rdlock(&_rwlock);
        std::cout << "读者-" << *id << " read data ->" << Data << std::endl;
        pthread_rwlock_unlock(&_rwlock);
        // 处理读取到的数据
        //sleep(1);
    }
    delete id;
}
void *Writer(void *args)
{
    int *id = static_cast<int *>(args);
    while (true)
    {
        pthread_rwlock_wrlock(&_rwlock);
        Data = rand() % 45562;
        std::cout << "写者-" << *id << " write data ->" << Data << std::endl;
       // sleep(2);
        pthread_rwlock_unlock(&_rwlock);
    }
    delete id;
}
int main()
{
    srand(time(nullptr));
    const int ReadNum = 1;
    const int WriteNum = 100;
    const int totalNum = ReadNum + WriteNum;
    pthread_t threads[totalNum];
    // 读者
    for (int i = 0; i < ReadNum; i++)
    {
        int *tid = new int(i + 1);
        pthread_create(&threads[i], nullptr, Reader, tid);
    }
    // 写者
    for (int i = WriteNum; i < totalNum; i++)
    {
        int *tid = new int(i - WriteNum + 1);
        pthread_create(&threads[i], nullptr, Writer, tid);
    }
    // 等待
    for (int i = 0; i < totalNum; i++)
    {
        pthread_join(threads[i], nullptr);
    }

    return 0;
}